<script setup lang="ts">
import {
  ConsultOrder,
  getConsultPreOrder, getPatientDetailInfo
} from '@/apis/consult';
import router from '@/router';
import { useConsultStore } from '@/stores/modules/consult';
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult';
import type { Patient } from '@/types/user';
import { showConfirmDialog, showToast } from 'vant';
import { onMounted, ref } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';

defineOptions({
  name: 'ConsultPay'
})
const payInfo = ref<ConsultOrderPreData>()
const store = useConsultStore()
const prePayInfoList = async () => {
  const res = await getConsultPreOrder({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  })
  payInfo.value = res.data
}
const patientInfo = ref<Patient>()
const patientInfoList = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientDetailInfo(store.consult.patientId)
  patientInfo.value = res.data
}
//
type Key = keyof PartialConsult
onMounted(() => {
  //定义一个数组，保存填写记录的字段名
  const validArr: Key[] = ['type', 'illnessType', 'consultFlag', 'illnessDesc', 'depId', 'illnessTime', 'patientId']
  const isValue = validArr.every((item) => store.consult[item] !== undefined)
  if (!isValue) {
    showConfirmDialog({
      title: '温馨提示',
      message: '信息不完整重新填写，有订单未提交可前往我的订单进行支付',
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
  }
  prePayInfoList()
  patientInfoList()
})
const isAgree = ref(false)
const show = ref(false)
const loading = ref(false)
const orderId = ref('')
const onSubmit = async () => {
  if (!isAgree.value) return showToast('请勾选支付协议')
  loading.value = true
  const res = await ConsultOrder(store.consult)
  orderId.value = res.data.id
  loading.value = false
  //清除仓库的缓存
  store.clear()
  // console.log(store.consult);

  show.value = true
}
//阻止点击返回上一页
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})
const onClose = () => {
  return showConfirmDialog({
    title: '温馨提示',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    confirmButtonText: '继续支付',
    cancelButtonText: '取消支付'
  }).then(() => {
    return false
  }).catch(() => {
    orderId.value = ''
    router.push('/user/consult')
    return false
  })

}
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo && patientInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payInfo.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell title="患者信息"
        :value="`${patientInfo?.name} | ${patientInfo?.genderValue} | ${patientInfo?.age}`"></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar :loading="loading" button-type="primary" :price="payInfo.actualPayment * 100" button-text="立即支付"
      text-align="left" @click="onSubmit" />
    <cp-pay-sheet pay-callback="/room" v-model:show="show" :order-id="orderId" :onClose="onClose"
      :actual-payment="payInfo.actualPayment"></cp-pay-sheet>
  </div>
  <!-- 骨架屏 -->
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付" />
    <van-skeleton title avatar :row="3" />
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}

.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;

  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }

  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }

  .desc {
    flex: 1;

    >span {
      display: block;
      color: var(--cp-tag);

      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}

.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }

    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}

.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}

.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;

  .text {
    color: var(--cp-primary);
  }
}

::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
</style>